package com.yequan.io;

import org.apache.commons.io.FileUtils;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author yq
 * @date 2020/07/02
 */
public class FileReadDemo {

    public static void main(String[] args) throws IOException {
        long startTime = System.currentTimeMillis();
        channelReadTest();
//        bufferReaderTest();
//        fileUtilsReadTest();
        long consumeTime = System.currentTimeMillis() - startTime;
        System.out.println("耗时:" + consumeTime + " ms");
    }

    /**
     * 读取文件效率很高
     *
     * @throws IOException
     */
    public static void channelReadTest() throws IOException {
        FileChannel inChannel = FileChannel.open(Paths.get("E:\\TEMP\\read.txt"), StandardOpenOption.READ);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (inChannel.read(byteBuffer) > 0) {
            byteBuffer.flip();
            System.out.println(Charset.forName("gbk").decode(byteBuffer));
            byteBuffer.clear();
        }
    }

    /**
     * 效率很高与channelReadTest差不多
     *
     * @throws IOException
     */
    public static void fileUtilsReadTest() throws IOException {
        String content = FileUtils.readFileToString(new File("E:\\TEMP\\read.txt"), "gbk");
        System.out.println(content);
    }

    /**
     * 效率差
     *
     * @throws IOException
     */
    public static void bufferReaderTest() throws IOException {
        BufferedReader rdr = Files.newBufferedReader(Paths.get("E:\\TEMP\\read.txt"), Charset.forName("gbk"));
        String line = null;
        while ((line = rdr.readLine()) != null) {
            System.out.println(line);
        }
    }

}
